package seven.test_7_10;

import java.util.ArrayList;

public class Solution {
    public boolean exist (String[] board, String word) {
        // write code here
       int a = board.length;
       int b = board[0].length();
       char[][] arr = new char[a][b];
       for (int i = 0; i < a; i++) {
           for (int j = 0; j < b; j++) {
               arr[i][j] = board[i].charAt(j);
           }
       }
       return existSon(arr,word);
    }
    private boolean existSon(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if (dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
        if (k == word.length - 1) return true;
        board[i][j] = '\0';
        boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
                dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
        board[i][j] = word[k];
        return res;
    }

}
